package logic

import (
	"context"
	"fmt"
	"novel/model/cache"
	"novel/model/mysql"
	"strconv"

	"novel/novelrpc/internal/svc"
	"novel/novelrpc/novelrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ForgetPasswordLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewForgetPasswordLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ForgetPasswordLogic {
	return &ForgetPasswordLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 忘记密码
func (l *ForgetPasswordLogic) ForgetPassword(in *novelrpc.ForgetPasswordRequest) (*novelrpc.ForgetPasswordResponse, error) {
	// todo: add your logic here and delete this line

	Sms, _ := cache.Rdb.Get(l.ctx, "SendsKey"+in.Account).Int64()
	if Sms != in.SendSms {
		return nil, fmt.Errorf("验证码不正确,请稍后再试")
	}

	var user mysql.User
	mysql.DB.Where("account=?", in.Account).Find(&user)
	if user.ID == 0 {
		return nil, fmt.Errorf("该用户不存在")
	}
	if in.Password != in.NewPassword {
		return nil, fmt.Errorf("两次输入的密码不一致,请重试")
	}

	user.Password = in.Password
	mysql.DB.Debug().Updates(&user)

	return &novelrpc.ForgetPasswordResponse{
		UserId: strconv.Itoa(int(user.ID)),
	}, nil
}
